<?php
/**
 * Created by JieHuiLong.
 * E-mail: jiehuilong@icloud.com
 * Date: 2016/8/16
 * Time: 16:00
 * 广告分组管理控制器
 */

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Controllers\Controller;
use App\Http\Requests\GroupAttrCreateRequest;
use App\Http\Requests\GroupAttrUpdateRequest;
use App\Models\Group;
use App\Models\Domain;
use App\Models\GroupAttributes as GroupAttr;
use App\Models\DomainAttributes as DomainAttr;

use App\Models\AdminUser as User;
use App\Models\Templates;
use Cache;
use DB;

class GroupAttrController extends Controller
{
    protected $fields = [
        'uid' => '',
        'username' => '',
        'gid' => '',
        'gname' => '',
        'type' => '',
        'type_value' => '',
        'name' => '',
        'value' => '',
        'call_tag' => '',
    ];

    public function __construct(Request $request)
    {
        $this->gid = $request->get('gid')?$request->get('gid'):0;
        if( $this->gid != 0 ){
            $this->groupName =Group::where('id', $this->gid )->value('title');
        }
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = array();
        if ($request->ajax()) {
            $data = array();
            $data['draw'] = $request->get('draw');
            $start = $request->get('start');
            $length = $request->get('length');
            $order = $request->get('order');
            $columns = $request->get('columns');
            $search = $request->get('search');
            $gid = $request->get('gid');
            $gidCondition = $gid ? [['gid', '=', $gid],] : [['gid', '>', 0],];
            $data['recordsTotal'] = GroupAttr::where(session('authAdminCondition'))->count();
            if (strlen($search['value']) > 0) {
                $data['recordsFiltered'] = GroupAttr::where(function ($query) use ($search) {
                    $query->where('gname', 'LIKE', '%' . $search['value'] . '%')
                        ->orWhere('call_tag', 'like', '%' . $search['value'] . '%');
                })->where(session('authAdminCondition'))
                    ->where($gidCondition)->count();

                $data['data'] = GroupAttr::where(function ($query) use ($search) {
                    $query->where('gname', 'LIKE', '%' . $search['value'] . '%')
                        ->orWhere('call_tag', 'like', '%' . $search['value'] . '%');
                })->where(session('authAdminCondition'))->where($gidCondition)
                    ->skip($start)->take($length)
                    ->orderBy($columns[$order[0]['column']]['data'], $order[0]['dir'])
                    ->get();
            } else {
                //$data['recordsFiltered'] = GroupAttr::where($gidCondition)->count();
				$data['recordsFiltered'] = $data['recordsTotal'];
                $data['data'] = GroupAttr::where($gidCondition)->where(session('authAdminCondition'))
                    ->skip($start)->take($length)
                    ->orderBy($columns[$order[0]['column']]['data'], $order[0]['dir'])
                    ->get();
            }
            return response()->json($data);

        }

        if( $this->gid != 0 ){
            $data['groupId'] = $this->gid;
            $data['groupName'] = $this->groupName;
        }
        return view('admin.groupAttr.index', $data);
//        return Redirect::back();
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Request $request)
    {
        $data = [];
        foreach ($this->fields as $field => $default) {
            $data[$field] = old($field, $default);
        }
        $data['groupList'] = Group::where(session('authAdminCondition'))->select('id', 'title', 'uid', 'username')->get();
        $data['gid'] = $request->gid ? (int)$request->gid : 0;
        foreach ($data['groupList'] as $key => $obj) {
            if ($obj->id == $data['gid']) {
                $data['groupList'][$key] = $data['groupList'][0];
                $data['groupList'][0] = $obj;
            }
        }
        if( $this->gid != 0 ){
            $data['groupId'] = $this->gid;
            $data['groupName'] = $this->groupName;
        }

        return view('admin.groupAttr.create', $data);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(GroupAttrCreateRequest $request)
    {
        $groupAttr = new GroupAttr();
        foreach (array_keys($this->fields) as $field) {
            $groupAttr->$field = trim($request->get($field));
        }
        $id = GroupAttr::where(["gid" => $groupAttr->gid, "call_tag" => $groupAttr->call_tag])->value('id');
        if ($id) {
            return back()->withErrors('添加失败！【调用标签】不能重复，请您使用其他标签名');
        }
		event(new \App\Events\userActionEvent('\App\Models\GroupAttr',$groupAttr->id, 1, '新增分组调用标签['.$groupAttr->name.']' ));
        $groupAttr->save();

        //保存分组新属性
//        $groupAttr->save();

        //为所属分组域名增加新属性
        $domainAttrList = Domain::where('gid', $groupAttr->gid)->groupBy('domain')->get();

        $record = array();
        $recordArr = array();
        if (count($domainAttrList)) {
            $domainAttr = new DomainAttr();
            foreach (array_keys($this->fields) as $field) {
                $domainAttr->$field = $request->get($field);
            }
            $record['gaid'] = $groupAttr->id;
            $record['ganame'] = $request->gname;
            foreach (array_keys($this->fields) as $field) {
                $record[$field] = $request->get($field);
            }
            unset($record['gname']);
            foreach ($domainAttrList as $Dkey => $DRow) {
                $record['did'] = $DRow['id'];
                $record['domain'] = $DRow['domain'];
                $id = DomainAttr::where(["did" => $record['did'], "call_tag" => $record['call_tag']])->value('id');
                if (!$id) {
                    $recordArr[] = $record;
                    DomainAttr::insert($record);
                }
            }
//            DomainAttr::insert($recordArr);
        }
			$userToken = Cache::rememberForever('userToken', function () {
				$tokenUid = auth()->user()->id;
				$token = DB::table('tokens');
				$userToken = $token->where('uid', '=', $tokenUid)->value('token');
				if ($userToken === null) {
					$userToken = $this->createToken($tokenUid);
				}
				return $userToken;
			});
			$domains = Domain::where('gid',$groupAttr->gid)->get();
			foreach($domains as $domain){
				$this->crossUpTpl2($domain->id,$domain->tpl_id,$userToken);
			}
        return redirect('/admin/groupAttr?gid=' . $groupAttr->gid)->withSuccess('添加成功！' . count($recordArr));
        //return redirect('/admin/groupAttr')->withSuccess('添加成功！');
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $groupAttr = GroupAttr::find((int)$id);
        if (!$groupAttr) return redirect('/admin/groupAttr')->withErrors("找不到该属性!");
        foreach (array_keys($this->fields) as $field) {
            $data[$field] = old($field, $groupAttr->$field);
        }
        $data['id'] = (int)$id;
        $data['groupList'] = Group::where(session('authAdminCondition'))->select('id', 'title', 'uid', 'username')->get();
        $data['groupId'] = $groupAttr->gid;
        $data['groupName'] = $groupAttr->gname;

        return view('admin.groupAttr.edit', $data);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(GroupAttrUpdateRequest $request, $id)
    {

        $groupAttr = GroupAttr::find((int)$id);
        foreach (array_keys($this->fields) as $field) {
            $groupAttr->$field = trim($request->get($field));;
        }
        $id = GroupAttr::where(["gid" => $groupAttr->gid, "call_tag" => $groupAttr->call_tag])->value('id');
        if ($id && $groupAttr->call_tag != $groupAttr->call_tag) {
            return back()->withErrors('添加失败！【调用标签】不能重复，请您使用其他标签名');
        } else {
			event(new \App\Events\userActionEvent('\App\Models\GroupAttr',$id, 3, '更新分组调用标签['.$groupAttr->name.']'));
            $groupAttr->save();
        }

        if ($request->cover === 'cover') {
            //对应配置进行覆盖
            $coverData['gid'] = $groupAttr->gid;
            $coverData['ganame'] = $groupAttr->gname;
            $coverData['type'] = $groupAttr->type;
            $coverData['type_value'] = $groupAttr->type_value;
            $coverData['name'] = $groupAttr->name;
            $coverData['value'] = $groupAttr->value;
            $coverData['call_tag'] = $groupAttr->call_tag;
            DomainAttr::where('gaid', $groupAttr->id)->update($coverData);
        }
		$userToken = Cache::rememberForever('userToken', function () {
				$tokenUid = auth()->user()->id;
				$token = DB::table('tokens');
				$userToken = $token->where('uid', '=', $tokenUid)->value('token');
				if ($userToken === null) {
					$userToken = $this->createToken($tokenUid);
				}
				return $userToken;
			});
			$domains = Domain::where('gid',$groupAttr->gid)->get();
			foreach($domains as $domain){
				$this->crossUpTpl2($domain->id,$domain->tpl_id,$userToken);
			}
        return redirect('/admin/groupAttr?gid=' . $groupAttr->gid)->withSuccess('更新成功！');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id or string ids=>1,2,3,4,5,6
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        if (is_numeric($id)) {
            $tag = GroupAttr::find((int)$id);
            if ($tag) {
                $gid=$tag->gid;
				$name=$tag->name;
                $tag->delete();
				event(new \App\Events\userActionEvent('\App\Models\GroupAttr',$id, 2, '删除了分组标签['.$name.']'));
				$userToken = Cache::rememberForever('userToken', function () {
					$tokenUid = auth()->user()->id;
					$token = DB::table('tokens');
					$userToken = $token->where('uid', '=', $tokenUid)->value('token');
					if ($userToken === null) {
						$userToken = $this->createToken($tokenUid);
					}
					return $userToken;
				});
				$domains = Domain::where('gid',$gid)->get();
				foreach($domains as $domain){
					$this->crossUpTpl2($domain->id,$domain->tpl_id,$userToken);
				}
                DomainAttr::where('gaid', $id)->delete();
				
            } else {
                return redirect()->back()
                    ->withErrors("删除失败");
            }
        } else {
            $idArr = explode(',', $id);
			foreach($idArr as $ids){
				$userToken = Cache::rememberForever('userToken', function () {
					$tokenUid = auth()->user()->id;
					$token = DB::table('tokens');
					$userToken = $token->where('uid', '=', $tokenUid)->value('token');
					if ($userToken === null) {
						$userToken = $this->createToken($tokenUid);
					}
					return $userToken;
				});
				 $tag = GroupAttr::find((int)$ids);
				$domains = Domain::where('gid',$tag>gid)->get();
				foreach($domains as $domain){
					$this->crossUpTpl2($domain->id,$domain->tpl_id,$userToken);
				}
			}
			$names='';
			$gas = GroupAttr::whereIn('id', $idArr)->get();
			foreach($gas as $ga){$names.=$ga->name."、";}
            $recordRow = GroupAttr::whereIn('id', $idArr)->delete();
			event(new \App\Events\userActionEvent('\App\Models\GroupAttr',0, 2, '删除了分组标签['.$names.']'));
            DomainAttr::whereIn('gaid', $idArr)->delete();
            if (!$recordRow) {
                return redirect()->back()
                    ->withErrors("删除失败");
            }
        }
        return redirect()->back()
            ->withSuccess("删除成功");
    }
	public function crossUpTpl2($id,$tpl_id,$userToken){
        //获取域名信息
        $domain = Domain::find((int)$id);
        //获取域名属性
        $listsAttr = DomainAttr::where('did', $id)->get();
        $dataAttr = [];
        foreach ($listsAttr as $rowKey => $row) {
            $dataAttr[$row['call_tag']] = $row['value'];
        }
        //读取推广模板信息
        $sourceCode = htmlentities(Templates::where('id', $tpl_id)->value('source_code'));
        $sourceCode = $this->replaceTpLable($dataAttr, $sourceCode);
        //读取审核模板信息
        $sh_tpl_id = Group::where('id', $domain->gid)->value('sh_tpl_id');
        $sourceCodeCompany = htmlentities(Templates::where('id', $sh_tpl_id)->value('source_code'));
        $sourceCodeCompany = $this->replaceTpLable($dataAttr, $sourceCodeCompany);
        //把最新的模板保存到数据中
        $data['uid'] = $domain->uid;
        $data['username'] = $domain->username;
        $data['did'] = $domain->id;
        $data['gid'] = $domain->gid;
        $data['domain'] = $domain->domain;
        $data['html'] = $sourceCode;
        $time = time();
		$data['token'] = md5($userToken . $time);
        $newSkins = DB::table('new_skins');

        $newSkins->where('did', $domain->id)->delete();
        //保存推广模板
        $newSkins->insert($data);
        //保存审核模板
        $data['html'] = $sourceCodeCompany;
        $data['token'] = md5($data['token'] . $data['did']);
        $newSkins->insert($data);

        $data['directory']= $domain->directory;

        $url =  $domain->access_type.'://'.$domain->domain;
		 $url .= "/upgrade.php";
		$data['time'] =$time;
		if(httpcode($url)==200){
			event(new \App\Events\userActionEvent('\App\Models\Domain',$id, 3, '更新域名['.$domain->domain.']的模板['.Templates::where('id', $tpl_id)->value('name').']生成到前台'));
			return $this->curlPost($url,$data);
		}else{
			return "error";
		}
	}
	public function curlPost($url,$data){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		// post数据
		curl_setopt($ch, CURLOPT_POST, 1);
		// post的变量
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		$output = curl_exec($ch);
		curl_close($ch);
		return $output;
	}
	 protected function replaceTpLable($dataAttr, $sourceCode)
    {
        //循环替换模板标签属性
        foreach ($dataAttr as $key => $value) {
            $sourceCode = str_replace("{{" . $key . "}}", $value, $sourceCode);
        }
        $sourceCode = str_replace('{{$', "<?php echo \$data['", $sourceCode);
        $sourceCode = str_replace('$}}', "'];?>", $sourceCode);
        //清空不存在的值
        $sourceCode = preg_replace("/{{(.*?)}}/", '', $sourceCode);
        $sourceCode = html_entity_decode($sourceCode);
        return $sourceCode;
    }
}